from flask import Blueprint,request,jsonify
import json
from db import db1
from utils.redisc import red
bp_work = Blueprint('workflow',__name__)

@bp_work.route('worklist')
def worklist():
    sql = "select * from workflow"
    res = db1.findall(sql)
    return  jsonify({'code':200,'list':res})

# 获取数据源
@bp_work.route('getsourcedata')
def getsourcedata():
    # 从redis取，如果有直接返回
    values = red.find_set('dataresouce')
    if values:
        list = eval(values)
    else:
        sql="select * from data_source"
        res = db1.findall(sql)
        list=[]
        if res:
            for i in res:
                dict = {'id':i['id'],'name':i['name']}
                sql1 = "select id,name,type from %s"%(i['tablename'])
                subres = db1.findall(sql1)
                dict['mes']=subres
                list.append(dict)
                print(list)
        red.insert_set('dataresouce',json.dumps(list))
    return jsonify({'code':200,'list':list})


@bp_work.route('/setparmas',methods=['POST'])
def setparmas():
    data = request.data
    if data:
        data = json.loads(data)
    else:
        data = request.form
    sql = "update workflow set parmas='%s' where id=%d "%(data['mes'],int(data['id']))
    db1.update(sql)
    return jsonify({'code':200})

@bp_work.route('/getparmas')
def getparmas():
    id  = request.args.get('id')
    sql = "select parmas from workflow where id=%d"%(int(id))
    res = db1.find(sql)
    # print(res)
    return jsonify({'code':200,'list':res})


@bp_work.route('/holiday',methods=['POST'])
def holiday():
    # data = request.form.to_dict()
    data = request.data
    if data:
        data = json.loads(data)
    else:
        data = request.form
    print(data)
    sql = "insert into tast(title,parmas,next_audit,status) values('%s','%s','%s',1)"%(data['title'],data['pic'],data['list'])
    print(sql)
    db1.update(sql)
    # 把当前任务加到redis里，先用hash
    sql = "select id,title from tast where title='%s'"%(data['title'])
    task = db1.find(sql)
    key='task%s'%(data['pic'][0])
    red.insert_hash(key,task['id'],task['title'])
    return jsonify({'code':200})

@bp_work.route('/jueseM')
def jueseM():
    sql = "select name from jue_se"
    res = db1.findall(sql)
    return jsonify({'code':200,'list':res['name']})

def pre(data):
    tree={}
    list=[]
    for i in data:
        tree[i['id']]=i
    for j in data:
        pid = j['pid']
        if not pid:
            list.append(j)
        else:
            if 'children' not in tree[pid]:
                tree[pid]['children']=[]
            # 查询此部门下所有员工
            sql = "select * from user where organization_id=%d"%(j['id'])
            res = db1.findall(sql)
            userlist = []
            if res:
                for u in res:
                    u['type']=3
                    userlist.append(u)

            j['children'] = userlist
            tree[pid]['children'].append(j)
    return list


@bp_work.route('/getpeople')
def getpeople():
    sql = "select * from organization"
    res = db1.findall(sql)
    list = pre(res)
    return jsonify({'code':200,'list':list})



@bp_work.route('getwork')
def getwork():
    id = request.args.get('id')
    if id:
        sql = "select * from tast where id=%d"%(int(id))
        res = db1.find(sql)
    else:
        userid = request.args.get('userid')
        sql = "select * from tast where status=1 and next_audit=%d"%(int(userid))
        res = db1.findall(sql)
    return jsonify({'code':200,'list':res})

import datetime
@bp_work.route('/taskrecordM',methods=['POST'])
def taskrecordM():
    data = request.data
    if data:
        data = json.loads(data)
    else:
        data = request.form
    # print(data)
    # add_time =datetime.datetime.strftime(datetime.datetime.now(),'%Y-%m-%d %H:%M:%S')
    # sql = "insert into audit_records(taskid,userid,username,is_agree,reason,add_time) values(%d,%d,'%s',%d,'%s','%s')"%(int(data['id']),int(data['userid']),data['username'],int(data['is_agree']),data['reason'],add_time)
    # db1.update(sql)
#     判断是否同意、
    tsql = "select * from tast where id=%d"%(int(data['id']))
    task = db1.find(tsql)
    lst = []
    # 删除当前redis中的信息
    print(task)
    key = 'task%d'%(int(task['id']))
    red.del_hash(key,int(data['id']))
    auditlist = json.loads(task['next_audit'])
    print(auditlist)
    lst.append(auditlist)
    print(lst)
    index = lst.index(int(data['userid']))
# 同意,查询任务，更新下一审批人，redis清除当前审批人，加入下一审批人
    if data['is_agree']==1 :
        #  任务表中更新任务状态，如果是最后一个审批人，更新成已经完成，其他为审核中
        if index == len(auditlist)-1:
            sql1 = "update tast set status=3,nexta=0 where id=%d"%(int(task['id']))
            db1.update(sql1)
        else:
            sql2 = "update tast set status=2,nexta=%d where id=%d" % (auditlist[index+1],int(task['id']))
            db1.update(sql2)
            # 添加redis
            newkey = 'task%d'%(int(auditlist[index+1]))
            # 把下一审批人加入到redis
            red.insert_hash(newkey,int(data['id']),task['title'])

    else:
        if index == 0:
            sql3="update tast set status=1,nexta=0 where id=%d"%(int(data['id']))
            db1.update(sql3)
        else:
            sql1 = "update tast set nexta=%d where id=%d" % (int(auditlist[index - 1]), int(data['taskid']))
            db1.update(sql1)
            # 添加redis
            newkey = 'task%d' % (int(auditlist[index - 1]))
            # 把下一审批人加入到redis
            red.insert_hash(newkey, int(data['taskid']), task['title'])
    return jsonify({'code':200})


@bp_work.route('/gettask')
def gettask():
    sql = "select * from tast"
    res = db1.findall(sql)
    return jsonify({'code':200,'list':res})